<template>
  <div class="guild-contribution-manage">
    <h2>公会贡献管理</h2>

    <!-- 加载状态 -->
    <el-skeleton :loading="loading" animated v-if="!contributions.length && totalRecords === 0"></el-skeleton>

    <el-table :data="contributions" style="width: 100%" border v-else>
      <el-table-column prop="id" label="贡献ID" align="center"></el-table-column>
      <el-table-column prop="guildId" label="公会ID" align="center"></el-table-column>
      <el-table-column prop="playerId" label="玩家ID" align="center"></el-table-column>
      <el-table-column prop="contribution" label="贡献值" align="center"></el-table-column>
      <el-table-column prop="recordTime" label="记录时间" align="center">
        <template #default="scope">
          {{ formatDate(scope.row.recordTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 空数据状态 -->
    <div v-if="totalRecords === 0 && !loading" class="empty-state">
      <el-empty description="暂无贡献记录"></el-empty>
    </div>

    <div style="margin-top: 10px; display: flex; align-items: center;">
      <el-button type="primary" @click="showCreateDialogWithGuildId">添加贡献记录</el-button>
      <el-button @click="resetPagination">查询所有贡献记录</el-button>
      <el-input
          v-model="searchGuildId"
          placeholder="按公会ID筛选"
          style="width: 200px; margin-left: 10px"
          @keyup.enter="fetchContributionsByGuildId"
      />
      <el-input
          v-model="searchPlayerId"
          placeholder="按玩家ID筛选"
          style="width: 200px; margin-left: 10px"
          @keyup.enter="fetchContributionsByPlayerId"
      />
    </div>

    <!-- 分页组件 -->
    <el-pagination
        v-if="totalRecords > 0"
        @size-change="handlePageSizeChange"
        @current-change="handleCurrentPageChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalRecords"
    />

    <!-- 新增贡献记录表单对话框 -->
    <el-dialog title="添加贡献记录" v-model="dialogVisible" width="30%">
      <el-form :model="contributionForm" :rules="rules" ref="formRef">
        <el-form-item label="公会ID" prop="guildId">
          <el-input v-model.number="contributionForm.guildId" placeholder="请输入公会ID" />
        </el-form-item>
        <el-form-item label="玩家ID" prop="playerId">
          <el-input v-model.number="contributionForm.playerId" placeholder="请输入玩家ID" />
        </el-form-item>
        <el-form-item label="贡献值" prop="contribution">
          <el-input v-model.number="contributionForm.contribution" type="number" placeholder="请输入贡献值" />
        </el-form-item>
        <el-form-item label="记录时间" prop="recordTime">
          <el-date-picker
              v-model="contributionForm.recordTime"
              type="datetime"
              placeholder="选择记录时间"
              value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑贡献记录对话框 -->
    <el-dialog title="编辑贡献记录" v-model="editDialogVisible" width="30%">
      <el-form :model="editContributionForm" :rules="rules" ref="editFormRef">
        <el-form-item label="公会ID">
          <el-input v-model.number="editContributionForm.guildId" disabled />
        </el-form-item>
        <el-form-item label="玩家ID" prop="playerId">
          <el-input v-model.number="editContributionForm.playerId" />
        </el-form-item>
        <el-form-item label="贡献值" prop="contribution">
          <el-input v-model.number="editContributionForm.contribution" type="number" />
        </el-form-item>
        <el-form-item label="记录时间" prop="recordTime">
          <el-date-picker
              v-model="editContributionForm.recordTime"
              type="datetime"
              placeholder="选择记录时间"
              value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateContribution">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import request from "@/utils/request";
import dayjs from "dayjs";

// 从本地存储获取token
const getToken = () => localStorage.getItem('token') || '';

// 数据状态
const contributions = ref([]);
const loading = ref(false);
const searchGuildId = ref('');
const searchPlayerId = ref('');
const formRef = ref(null);
const editFormRef = ref(null);

// 分页状态
const currentPage = ref(1);
const pageSize = ref(10);
const totalRecords = ref(0);

// 对话框状态
const dialogVisible = ref(false);
const editDialogVisible = ref(false);
const isEdit = ref(false);

// 表单数据
const contributionForm = reactive({
  id: null,
  guildId: null,
  playerId: null,
  contribution: null,
  recordTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
});

const editContributionForm = reactive({
  id: null,
  guildId: null,
  playerId: null,
  contribution: null,
  recordTime: null
});

// 表单验证规则
const rules = {
  guildId: [{ required: true, message: '请输入公会ID', trigger: 'blur' }],
  playerId: [{ required: true, message: '请输入玩家ID', trigger: 'blur' }],
  contribution: [
    { required: true, message: '请输入贡献值', trigger: 'blur' },
    { type: 'number', message: '贡献值必须为数字', trigger: 'blur' }
  ],
  recordTime: [{ required: true, message: '请选择记录时间', trigger: 'change' }]
};

// 日期格式化
const formatDate = (dateString) => {
  if (!dateString) return '无记录';
  try {
    return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss');
  } catch (error) {
    return '格式错误';
  }
};

// 获取所有贡献记录（带分页）
const fetchAllContributions = async (page = currentPage.value, size = pageSize.value) => {
  try {
    loading.value = true;
    const params = {
      page,
      size,
      sort: 'recordTime',
      order: 'desc'
    };
    const response = await request.get('/guild/contributions/all', {
      params,
      headers: { 'Authorization': getToken() }
    });

    if (response.code === 200 && response.data && response.data.records) {
      contributions.value = response.data.records.map(contribution => ({
        ...contribution,
        recordTime: contribution.recordTime ? dayjs(contribution.recordTime).format('YYYY-MM-DD HH:mm:ss') : null
      }));
      totalRecords.value = response.data.total;

      if (contributions.value.length === 0 && page > 1) {
        ElMessage.warning('当前页没有数据');
        currentPage.value = Math.max(1, page - 1);
        return fetchAllContributions(currentPage.value, pageSize.value);
      } else if (contributions.value.length === 0) {
        ElMessage.info('暂无贡献记录');
      } else {
        ElMessage.success('获取贡献记录成功');
      }
    } else {
      contributions.value = [];
      totalRecords.value = 0;
      ElMessage.warning('获取贡献记录失败');
    }
  } catch (error) {
    console.error('获取贡献记录失败:', error);
    handleApiError(error);
  } finally {
    loading.value = false;
  }
};

// 根据公会ID获取贡献记录（带分页）
const fetchContributionsByGuildId = async () => {
  const guildId = searchGuildId.value.trim();
  if (!guildId) {
    ElMessage.warning('请输入公会ID');
    return;
  }

  // 重置分页到第一页
  currentPage.value = 1;

  try {
    loading.value = true;
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      sort: 'recordTime',
      order: 'desc'
    };
    const response = await request.get(`/guild/${guildId}/contributions`, {
      params,
      headers: { 'Authorization': getToken() }
    });

    if (response.code === 200 && response.data && response.data.records) {
      contributions.value = response.data.records.map(contribution => ({
        ...contribution,
        recordTime: contribution.recordTime ? dayjs(contribution.recordTime).format('YYYY-MM-DD HH:mm:ss') : null
      }));
      totalRecords.value = response.data.total;

      if (contributions.value.length === 0) {
        ElMessage.info(`公会ID ${guildId} 没有贡献记录`);
      } else {
        ElMessage.success(`获取公会ID为 ${guildId} 的贡献记录成功`);
      }
    } else {
      contributions.value = [];
      totalRecords.value = 0;
      ElMessage.warning(`公会ID ${guildId} 没有贡献记录`);
    }
  } catch (error) {
    console.error('获取贡献记录失败:', error);
    handleApiError(error);
  } finally {
    loading.value = false;
  }
};

// 根据玩家ID获取贡献记录（带分页）
const fetchContributionsByPlayerId = async () => {
  const playerId = searchPlayerId.value.trim();
  if (!playerId) {
    ElMessage.warning('请输入玩家ID');
    return;
  }

  // 重置分页到第一页
  currentPage.value = 1;

  try {
    loading.value = true;
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      sort: 'recordTime',
      order: 'desc'
    };
    const response = await request.get(`/guild/player/${playerId}/contributions`, {
      params,
      headers: { 'Authorization': getToken() }
    });

    if (response.code === 200 && response.data && response.data.records) {
      contributions.value = response.data.records.map(contribution => ({
        ...contribution,
        recordTime: contribution.recordTime ? dayjs(contribution.recordTime).format('YYYY-MM-DD HH:mm:ss') : null
      }));
      totalRecords.value = response.data.total;

      if (contributions.value.length === 0) {
        ElMessage.info(`玩家ID ${playerId} 没有贡献记录`);
      } else {
        ElMessage.success(`获取玩家ID为 ${playerId} 的贡献记录成功`);
      }
    } else {
      contributions.value = [];
      totalRecords.value = 0;
      ElMessage.warning(`玩家ID ${playerId} 没有贡献记录`);
    }
  } catch (error) {
    console.error('获取贡献记录失败:', error);
    handleApiError(error);
  } finally {
    loading.value = false;
  }
};

// 显示创建对话框
const showCreateDialogWithGuildId = () => {
  dialogVisible.value = true;
  isEdit.value = false;
  resetForm(contributionForm);

  nextTick(() => {
    const guildIdInput = document.querySelector('.guild-contribution-manage input[placeholder="请输入公会ID"]');
    if (guildIdInput) guildIdInput.focus();
  });
};

// 显示编辑对话框
const showEditDialog = (contribution) => {
  editDialogVisible.value = true;
  isEdit.value = true;

  editContributionForm.id = contribution.id;
  editContributionForm.guildId = contribution.guildId;
  editContributionForm.playerId = contribution.playerId;
  editContributionForm.contribution = contribution.contribution;
  editContributionForm.recordTime = contribution.recordTime
      ? dayjs(contribution.recordTime).format('YYYY-MM-DD HH:mm:ss')
      : dayjs().format('YYYY-MM-DD HH:mm:ss');
};

// 重置表单数据
const resetForm = (form) => {
  form.id = null;
  form.guildId = null;
  form.playerId = null;
  form.contribution = null;
  form.recordTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
};

// 统一处理API错误
const handleApiError = (error) => {
  if (error.response) {
    const { status, data } = error.response;
    if (status === 401) {
      ElMessage.error('未授权，请重新登录');
      setTimeout(() => {
        window.location.href = '/login';
      }, 2000);
    } else if (data && data.message) {
      ElMessage.error(data.message);
    } else {
      ElMessage.error(`请求失败: ${status} ${error.message}`);
    }
  } else {
    ElMessage.error('网络连接失败，请检查网络设置');
  }
};

// 提交添加贡献记录表单
const submitForm = async () => {
  try {
    await formRef.value.validate();
    const response = await request.post('/guild/contribution', {
      ...contributionForm,
      recordTime: contributionForm.recordTime
    }, {
      headers: { 'Authorization': getToken() }
    });

    if (response.code === 200) {
      ElMessage.success('添加贡献记录成功');
      dialogVisible.value = false;
      await fetchAllContributions(currentPage.value, pageSize.value);
    } else {
      ElMessage.error(response.message || '添加贡献记录失败');
    }
  } catch (error) {
    console.error('添加贡献记录出错:', error);
    handleApiError(error);
  }
};

// 提交编辑贡献记录表单
const updateContribution = async () => {
  try {
    await editFormRef.value.validate();
    const response = await request.put('/guild/contribution', {
      ...editContributionForm,
      recordTime: editContributionForm.recordTime
    }, {
      headers: { 'Authorization': getToken() }
    });

    if (response.code === 200) {
      ElMessage.success('更新贡献记录成功');
      editDialogVisible.value = false;
      await fetchAllContributions(currentPage.value, pageSize.value);
    } else {
      ElMessage.error(response.message || '更新贡献记录失败');
    }
  } catch (error) {
    console.error('更新贡献记录出错:', error);
    handleApiError(error);
  }
};

// 删除贡献记录
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该贡献记录吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const response = await request.delete(`/guild/contribution/${id}`, {
      headers: { 'Authorization': getToken() }
    });

    if (response.code === 200) {
      ElMessage.success('删除贡献记录成功');
      await fetchAllContributions(currentPage.value, pageSize.value);
    } else {
      ElMessage.error(response.message || '删除贡献记录失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除贡献记录出错:', error);
      handleApiError(error);
    }
  }
};

// 重置分页到第一页
const resetPagination = () => {
  currentPage.value = 1;
  fetchAllContributions();
};

// 每页数量改变时的处理
const handlePageSizeChange = (newPageSize) => {
  pageSize.value = newPageSize;
  fetchAllContributions(currentPage.value, pageSize.value);
};

// 当前页码改变时的处理
const handleCurrentPageChange = (newPage) => {
  currentPage.value = newPage;
  fetchAllContributions(currentPage.value, pageSize.value);
};

onMounted(() => {
  // 检查是否已登录
  if (!getToken()) {
    ElMessage.warning('请先登录');
    setTimeout(() => {
      window.location.href = '/login';
    }, 2000);
    return;
  }

  fetchAllContributions();
});
</script>

<style scoped>
.guild-contribution-manage {
  padding: 20px;
}

.empty-state {
  margin-top: 20px;
  text-align: center;
}
</style>